package edu.neumont.csc380.hello.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.springframework.stereotype.Service;

import edu.neumont.csc380.hello.model.JmsGame;
import edu.neumont.csc380.hello.model.Move;
import edu.neumont.csc380.hello.model.Player;
import edu.neumont.csc380.hello.model.StatusMessage;

@Service("helloWorldService")
public class HelloWorldServiceImpl implements HelloWorldService {

	private List<JmsGame> currentGames = new ArrayList<JmsGame>();
	
	public JmsGame newGame() {
		Random randy = new Random();
		int gameId = 100000 + randy.nextInt(900000);
		for (JmsGame game : currentGames)
			if (game.gameId == gameId)
				gameId  = 100000 + randy.nextInt(900000);
		JmsGame newGame = new JmsGame(gameId);
		
		return newGame;
	}

	public Player addPlayer(JmsGame game, long publicKey) {
		int identifier = 0;
		if (game.playerCount == 0)
			identifier = -1;
		else
			identifier = 1;
		Player player = new Player(publicKey, game.gameId, identifier);
		game.addPlayer(player);
		return player;
	}

	public StatusMessage startGame(JmsGame game) {
		StatusMessage message = new StatusMessage("Game " + game.gameId + " Successfully Started");
		try {
			game.startGame();
		} catch (Exception ex) {
			message.message = "Game " + game.gameId + " failed to start";
		}
		return message;
	}

	public StatusMessage move(Move move, Player player) {
		StatusMessage message = new StatusMessage("Move " + move.getPosition() + " by Player: " + player.publicKey + " was successful.");
		try {
			JmsGame curGame = null;
			for (JmsGame game : currentGames)
				if (game.gameId == player.gameId)
					curGame = game;
			curGame.makeMove(move, player);
		} catch (Exception ex) {
			message = new StatusMessage("Move " + move.getPosition() + " by Player: " + player.publicKey + " was a complete failure.");
		}
		return message;
	}
	
//	NumberManager manager = new NumberManager();
//	
//	public boolean isPrime(int number) {
//		
//		return manager.isPrime(number);
//	}
//
//	public boolean areCoprime(String numbers) {
//		String[] strNums = numbers.split(",");
//		int[] nums = new int[strNums.length];
//		for(int i = 0; i < strNums.length; i++)
//			nums[i] = Integer.parseInt(strNums[i]);
//		
//		return manager.checkCoPrime(nums);
//	}


}
